<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getArticleById, recordView } from '../api/article'
import { toggleLike, checkLiked, toggleFavorite, checkFavorited, getComments, addComment, deleteComment } from '../api/interaction'
import { ElMessage, ElMessageBox } from 'element-plus'
import { CollectionTag, Pointer, Delete, View } from '@element-plus/icons-vue'
import { useUserStore } from '../stores/user'
import { generateColor } from '../utils/avatar'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css' // 可以选择其他主题

const md = new MarkdownIt({
    html: true,
    linkify: true,
    typographer: true,
    highlight: function (str, lang) {
        if (lang && hljs.getLanguage(lang)) {
            try {
                return '<pre class="hljs"><code>' +
                    hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +
                    '</code></pre>'
            } catch (__) {}
        }
        return '<pre class="hljs"><code>' + md.utils.escapeHtml(str) + '</code></pre>'
    }
})

const route = useRoute()
const router = useRouter()
const article = ref({})
const loading = ref(false)
const isLiked = ref(false)
const isFavorited = ref(false)
const comments = ref([])
const commentContent = ref('')
const replyTo = ref(null)
const userStore = useUserStore()

// 加载文章详情
const loadArticle = async () => {
    try {
        loading.value = true
        const res = await getArticleById(route.params.id)
        if (res.code === 200) {
            article.value = res.data
            // 加载点赞和收藏状态
            await Promise.all([
                checkLikeStatus(),
                checkFavoriteStatus(),
                loadComments()
            ])
            // 记录浏览记录
            await recordView(route.params.id)
        }
    } catch (error) {
        console.error('Load article error:', error)
        if (error.response?.status === 401) {
            ElMessage.warning('请先登录后查看文章详情')
            localStorage.setItem('redirect', route.fullPath)
            router.push('/')
        } else {
            ElMessage.error('加载文章失败')
        }
    } finally {
        loading.value = false
    }
}

// 检查点赞状态
const checkLikeStatus = async () => {
    // 只有登录用户才检查点赞状态
    if (!userStore.isLoggedIn) return
    
    try {
        const res = await checkLiked(article.value.id)
        isLiked.value = res.data
    } catch (error) {
        console.error('Failed to check like status:', error)
    }
}

// 点赞/取消点赞
const handleLike = async () => {
    if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
    }
    try {
        const res = await toggleLike(article.value.id)
        isLiked.value = res.data
        // 更新点赞数
        article.value.likeCount += isLiked.value ? 1 : -1
        ElMessage.success(isLiked.value ? '点赞成功' : '已取消点赞')
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
    // 只有登录用户才检查收藏状态
    if (!userStore.isLoggedIn) return
    
    try {
        const res = await checkFavorited(article.value.id)
        isFavorited.value = res.data
    } catch (error) {
        console.error('Failed to check favorite status:', error)
    }
}

// 收藏/取消收藏
const handleFavorite = async () => {
    if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录')
        return
    }
    try {
        const res = await toggleFavorite(article.value.id)
        isFavorited.value = res.data
        ElMessage.success(isFavorited.value ? '收藏成功' : '已取消收藏')
    } catch (error) {
        ElMessage.error('操作失败')
    }
}

// 加载评论列表
const loadComments = async () => {
    try {
        const res = await getComments(article.value.id)
        comments.value = res.data
    } catch (error) {
        console.error('Load comments error:', error)
    }
}

// 提交评论
const submitComment = async () => {
    // 检查登录状态
    if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录后再发表评论')
        localStorage.setItem('redirect', route.fullPath)
        router.push('/login')
        return
    }

    if (!commentContent.value.trim()) {
        ElMessage.warning('请输入评论内容')
        return
    }

    try {
        const data = {
            content: commentContent.value,
            articleId: article.value.id
        }
        
        if (replyTo.value) {
            data.parentId = replyTo.value.parentId || replyTo.value.id
            data.replyUserId = replyTo.value.userId
        }

        await addComment(data)
        ElMessage.success('评论成功')
        commentContent.value = ''
        replyTo.value = null
        await loadComments()
    } catch (error) {
        if (error.response?.status === 401) {
            ElMessage.warning('请先登录')
            localStorage.setItem('redirect', route.fullPath)
            router.push('/login')
        } else {
            ElMessage.error('评论失败')
        }
    }
}

// 回复评论
const replyComment = (comment) => {
    // 检查登录状态
    if (!userStore.isLoggedIn) {
        ElMessage.warning('请先登录后再回复评论')
        localStorage.setItem('redirect', route.fullPath)
        router.push('/login')
        return
    }
    
    replyTo.value = comment
    commentContent.value = `@${comment.username} `
}

// 删除评论
const handleDeleteComment = async (commentId) => {
    try {
        await ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
            type: 'warning'
        })
        
        await deleteComment(commentId)
        ElMessage.success('删除成功')
        await loadComments()
    } catch (error) {
        if (error !== 'cancel') {
            ElMessage.error('删除失败')
        }
    }
}

// 取消回复
const cancelReply = () => {
    replyTo.value = null
    commentContent.value = ''
}

// 渲染文章内容
const renderContent = computed(() => {
    return md.render(article.value.content || '')
})

onMounted(async () => {
    await loadArticle()
    await loadComments()
    // 只有登录用户才检查点赞和收藏状态
    if (userStore.isLoggedIn) {
        await checkLikeStatus()
        await checkFavoriteStatus()
    }
})
</script>

<template>
    <div v-loading="loading" class="article-container">
        <article v-if="article.id" class="article-content">
            <h1 class="title">{{ article.title }}</h1>
            <div class="article-meta">
                <div class="left">
                    <el-avatar
                      :size="32"
                      :style="{
                                backgroundColor: generateColor(article.authorName || ''),
                                color: '#fff',
                                fontSize: '16px'
                              }">
                    {{ (article.authorName || '').charAt(0).toUpperCase() }}
                  </el-avatar>
                    <span class="author">{{ article.authorName }}</span>
                    <span class="divider">|</span>
                    <span class="date">{{ new Date(article.createTime).toLocaleDateString() }}</span>
                    <span class="divider">|</span>
                    <span class="views">
                        <el-icon><View /></el-icon>
                        {{ article.viewCount || 0 }}
                    </span>
                </div>
                <div class="actions">
                    <el-button 
                        :type="isLiked ? 'primary' : 'default'"
                        @click="handleLike"
                        :icon="Pointer"
                    >
                        {{ isLiked ? '已点赞' : '点赞' }}
                    </el-button>
                    <el-button 
                        :type="isFavorited ? 'primary' : 'default'"
                        @click="handleFavorite"
                        :icon="CollectionTag"
                    >
                        {{ isFavorited ? '已收藏' : '收藏' }}
                    </el-button>
                </div>
            </div>

            <!-- 使用 v-html 渲染 markdown 内容 -->
            <div class="markdown-body" v-html="renderContent"></div>

            <div class="comments-section">
                <h3>评论 {{ comments.length }}</h3>
                <div class="comment-form" v-if="userStore.isLoggedIn">
                    <el-input
                        v-model="commentContent"
                        type="textarea"
                        :rows="3"
                        placeholder="写下你的评论..."
                    />
                    <div class="form-footer">
                        <span class="reply-tip" v-if="replyTo">
                            回复 @{{ replyTo.username }}
                            <el-button link type="info" @click="replyTo = null">取消回复</el-button>
                        </span>
                        <el-button type="primary" @click="submitComment">发表评论</el-button>
                    </div>
                </div>
                <div v-else class="comment-login-tip">
                    <el-empty description="登录后参与评论">
                        <el-button type="primary" @click="router.push('/login')">去登录</el-button>
                    </el-empty>
                </div>
                
                <div class="comments-list">
                    <template v-if="comments.length">
                        <div v-for="comment in comments" :key="comment.id" class="comment-item">
                            <div class="comment-header">
                                <el-avatar :size="40" :src="comment.userAvatar || '/default-avatar.png'" />
                                <div class="comment-info">
                                    <div class="username">{{ comment.username }}</div>
                                    <div class="time">{{ new Date(comment.createTime).toLocaleString() }}</div>
                                </div>
                            </div>
                            <div class="comment-content">
                                <template v-if="comment.replyUsername">
                                    <span class="reply-to">@{{ comment.replyUsername }}</span>
                                </template>
                                {{ comment.content }}
                            </div>
                            <div class="comment-actions">
                                <el-button link type="primary" @click="replyComment(comment)">回复</el-button>
                                <el-button 
                                    v-if="comment.userId === userStore.currentUser?.id"
                                    link 
                                    type="danger"
                                    @click="handleDeleteComment(comment.id)"
                                >
                                    <el-icon><Delete /></el-icon>
                                    删除
                                </el-button>
                            </div>
                            
                            <!-- 子评论 -->
                            <div v-if="comment.children?.length" class="sub-comments">
                                <div v-for="child in comment.children" :key="child.id" class="comment-item">
                                    <div class="comment-header">
                                        <el-avatar :size="32" :src="child.userAvatar || '/default-avatar.png'" />
                                        <div class="comment-info">
                                            <div class="username">{{ child.username }}</div>
                                            <div class="time">{{ new Date(child.createTime).toLocaleString() }}</div>
                                        </div>
                                    </div>
                                    <div class="comment-content">
                                        <template v-if="child.replyUsername">
                                            <span class="reply-to">@{{ child.replyUsername }}</span>
                                        </template>
                                        {{ child.content }}
                                    </div>
                                    <div class="comment-actions">
                                        <el-button link type="primary" @click="replyComment(child)">回复</el-button>
                                        <el-button 
                                            v-if="child.userId === userStore.currentUser?.id"
                                            link 
                                            type="danger"
                                            @click="handleDeleteComment(child.id)"
                                        >
                                            <el-icon><Delete /></el-icon>
                                        </el-button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </template>
                    <el-empty v-else description="暂无评论" />
                </div>
            </div>
        </article>
    </div>
</template>

<style scoped lang="scss">
$primary-color: #3eaf7c;
$text-color: #2c3e50;
$border-color: #eaecef;
$bg-light: #f8f9fa;
$transition: all 0.3s ease;

.article-container {
    width: 1000px;
    margin: 20px auto;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

    .article-content {
        padding: 40px;

        .title {
            font-size: 32px;
            font-weight: 600;
            color: $text-color;
            margin-bottom: 24px;
            line-height: 1.4;
            border-left: 4px solid $primary-color;
            padding-left: 16px;
        }

        .article-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 16px 24px;
            background: $bg-light;
            border-radius: 8px;
            margin-bottom: 40px;

            .left {
                display: flex;
                align-items: center;
                gap: 12px;

                .author {
                    color: $primary-color;
                    font-weight: 500;
                }

                .divider {
                    color: #ddd;
                }

                .date, .views {
                    color: #666;
                    font-size: 14px;
                }

                .views {
                    display: flex;
                    align-items: center;
                    gap: 4px;
                }
            }

            .actions {
                display: flex;
                gap: 12px;

                .el-button {
                    transition: $transition;

                    &:hover {
                        transform: translateY(-2px);
                    }
                }
            }
        }
    }
}

/* Markdown 样式 */
:deep(.markdown-body) {
    color: $text-color;
    line-height: 1.8;
    font-size: 16px;

    h1, h2, h3, h4, h5, h6 {
        margin-top: 36px;
        margin-bottom: 20px;
        font-weight: 600;
        line-height: 1.25;
    }

    h1, h2 {
        padding-bottom: 0.3em;
        border-bottom: 1px solid $border-color;
    }

    h1 {
        font-size: 2em;
    }

    h2 {
        font-size: 1.5em;
    }

    h3 {
        font-size: 1.25em;
    }

    p {
        margin-bottom: 20px;
    }

    pre {
        margin: 20px 0;
        padding: 20px;
        background: #282c34;
        border-radius: 8px;
        overflow-x: auto;
        font-size: 14px;
        line-height: 1.6;
        box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

        code {
            color: #abb2bf;
            background: none;
            padding: 0;
            border-radius: 0;
        }
    }

    code {
        padding: 0.2em 0.4em;
        font-size: 0.9em;
        background: rgba(27, 31, 35, 0.05);
        border-radius: 4px;
    }

    ul, ol {
        padding-left: 2em;
        margin: 16px 0;
    }

    li {
        margin: 8px 0;
    }

    blockquote {
        margin: 20px 0;
        padding: 12px 24px;
        background: $bg-light;
        border-left: 4px solid $primary-color;
        color: #666;
    }

    img {
        max-width: 100%;
        border-radius: 8px;
        margin: 16px 0;
    }

    table {
        width: 100%;
        margin: 16px 0;
        border-collapse: collapse;

        th, td {
            padding: 12px;
            border: 1px solid $border-color;
        }

        th {
            background: $bg-light;
            font-weight: 600;
        }

        tr:nth-child(2n) {
            background: #fafafa;
        }
    }
}

/* 评论区样式 */
.comments-section {
    margin-top: 60px;
    padding-top: 40px;
    border-top: 1px solid $border-color;

    h3 {
        font-size: 20px;
        font-weight: 600;
        margin-bottom: 24px;
        color: $text-color;
    }

    .comment-form {
        margin-bottom: 40px;
        padding: 20px;
        background: $bg-light;
        border-radius: 8px;
        border: 1px solid $border-color;
        transition: $transition;

        &:focus-within {
            border-color: $primary-color;
            box-shadow: 0 0 0 2px rgba($primary-color, 0.1);
        }

        .form-footer {
            margin-top: 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .reply-tip {
                color: #666;
                font-size: 14px;
            }
        }
    }

    .comment-login-tip {
        padding: 40px 0;
    }

    .comments-list {
        .comment-item {
            margin-bottom: 24px;
            padding-bottom: 24px;
            border-bottom: 1px solid $border-color;

            &:last-child {
                border-bottom: none;
            }

            .comment-header {
                display: flex;
                gap: 12px;
                margin-bottom: 12px;

                .comment-info {
                    .username {
                        font-weight: 500;
                        color: $text-color;
                        margin-bottom: 4px;
                    }

                    .time {
                        color: #999;
                        font-size: 12px;
                    }
                }
            }

            .comment-content {
                margin: 12px 0;
                color: $text-color;
                line-height: 1.6;
                font-size: 15px;

                .reply-to {
                    color: $primary-color;
                    margin-right: 8px;
                    font-weight: 500;
                }
            }

            .comment-actions {
                display: flex;
                gap: 16px;
                margin-top: 8px;
                opacity: 0;
                transition: $transition;
            }

            &:hover .comment-actions {
                opacity: 1;
            }

            .sub-comments {
                margin: 20px 0 0 52px;
                padding-left: 20px;
                border-left: 2px solid $border-color;

                .comment-item {
                    margin-bottom: 20px;
                    padding-bottom: 20px;

                    &:last-child {
                        margin-bottom: 0;
                        padding-bottom: 0;
                        border-bottom: none;
                    }
                }
            }
        }
    }
}

// 响应式处理
@media screen and (max-width: 1100px) {
    .article-container {
        width: auto;
        margin: 10px;
        border-radius: 0;

        .article-content {
            padding: 20px;
        }
    }
}
</style> 